package com.camemax.rabbitmq.simple_mode;

import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

/*
***************************
*   @Date: 2021-06-03
*   @Descript: RabbitMQ Consumer for rabbitMQ Simple Mode
***************************
*/
public class Consumer {
    public static void main(String[] args) {
        // 1. 创建RabbitMQ连接工厂
        ConnectionFactory rabbitmqConnFactory = new ConnectionFactory();

        // 2. 配置连接属性
        rabbitmqConnFactory.setHost("172.16.205.100");
        rabbitmqConnFactory.setPort(25672);
        rabbitmqConnFactory.setUsername("camemax");
        rabbitmqConnFactory.setPassword("123");
        rabbitmqConnFactory.setVirtualHost("/"); // 默认虚拟路径[/]

        // 3. 实例化连接Connection
        Connection connection = null;

        // 4. 实例化连接通道Channel
        Channel channel = null;

        // 5. 设置生产者-消费者队列名称
        String queueName = "test_queue";

        // 6. 配置连接管道
        try {
            // 6. 配置连接
            connection = rabbitmqConnFactory.newConnection("RabbitMQ Consumer");

            // 7. 通过连接配置管道
            channel = connection.createChannel();
            channel.basicConsume(
                    queueName
                    , true
                    , (consumer, message) -> System.out.println("RabbitMQ has accepts => [" + new String(message.getBody(), StandardCharsets.UTF_8)+ "]")
                    , consumer -> System.out.println("Consumer accepts failed!")
            );

            System.in.read(); // 持续性输出

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if( channel != null && channel.isOpen()){
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if ( connection != null && connection.isOpen()){
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
